package com.powernode.crm.activity.web;

import com.powernode.crm.activity.model.Activity;
import com.powernode.crm.activity.model.ActivityRemark;
import com.powernode.crm.activity.service.ActivityRemarkService;
import com.powernode.crm.activity.service.ActivityService;
import com.powernode.crm.commons.model.Constants;
import com.powernode.crm.commons.model.ResponseResult;
import com.powernode.crm.commons.utils.DateUtils;
import com.powernode.crm.commons.utils.UUIDUtils;
import com.powernode.crm.settings.model.User;
import com.powernode.crm.settings.service.UserService;
import com.powernode.crm.transaction.model.Tran;
import com.powernode.crm.transaction.service.TranService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private UserService userService;

    @Autowired
    private ActivityRemarkService activityRemarkService;

    @Autowired
    private TranService tranService;

    //    workbench/index
    @RequestMapping("/index")
    public String workBeanchIndex(Model model) {

        /*获取  所有者集合*/
        List<User> users = userService.queryAll();
        model.addAttribute("users", users);
        return "/workbench/activity/index";
    }

    /*活动详情*/

    @RequestMapping("/detail")
    public String detail(String id, Model model) {
        /*通过id获取 活动明细*/
        Activity activity = activityService.queryById(id);
        model.addAttribute("activity", activity);
        return "workbench/activity/detail";
    }

    @RequestMapping("/api/activityList")
    @ResponseBody
    public ResponseResult activityList(String name,
                                       String owner,
                                       String startDate,
                                       String endDate,
                                       Integer pageNum,
                                       Integer pageSize
    ) {

        System.out.println(name + owner);
        /*1 获取参数后 进行 处理*/
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        /*集合数据*/
        List<Activity> activities =
                activityService.queryPage(name, owner, startDate, endDate, pageNum, pageSize);
        /*页码*/
        /*总记录数*/
        int rows = activityService.queryListCount(name, owner, startDate, endDate);
        /*总页数*/
        int pages = rows % pageSize == 0 ? rows / pageSize : rows / pageSize + 1;
        /*通过map 封装数据*/
        Map<String, Object> data = new HashMap<>();
        data.put("activities", activities);
        data.put("pageNum", pageNum);
        data.put("rows", rows);
        data.put("pages", pages);
        data.put("pageSize", pageSize);
        /*将 map 存入  result*/
        ResponseResult result = new ResponseResult(Constants.STATUS_OK, "成功", data);
        return result;
    }


    /*添加*/
    @RequestMapping(value = "/api/addActivity", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult addActivity(Activity activity, HttpSession session) {
        ResponseResult result = new ResponseResult();

//        前端 传过来的 activity  缺少数据   id   createTime  createBy
        activity.setId(UUIDUtils.getUUID());
        activity.setCreateTime(DateUtils.formatDateTime(new Date()));
        User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
        activity.setCreateBy(loginUser.getId());
        /*保存*/
        int rows = activityService.addActivity(activity);
        if (rows > 0) {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("添加成功");
        } else {
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("添加失败");
        }
        return result;
    }

    /*通过id 获取  活动信息*/
    @RequestMapping("/api/getActivity")
    @ResponseBody
    public ResponseResult queryById(String id) {
        ResponseResult result = new ResponseResult();

        Activity activity = activityService.queryById(id);
        if (activity != null) {
            result.setCode(Constants.STATUS_OK);
            result.setData(activity);
        } else {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("查无此数据");
            result.setData(activity);
        }
        return result;
    }


    /*更新*/

    @RequestMapping("/api/updateActivity")
    @ResponseBody
    public ResponseResult updateActivity(Activity activity, HttpSession session) {
        ResponseResult result = new ResponseResult();
        /*赋予  修改时间 和 修改 人*/
        activity.setEditTime(DateUtils.formatDateTime(new Date()));
        User loginUser = (User) session.getAttribute(Constants.SESSION_USER);
        activity.setEditBy(loginUser.getId());
        int rows = activityService.modifyActivity(activity);
        if (rows > 0) {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("修改成功");
        } else {
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("修改失败");
        }

        return result;
    }

    /*删除*/
    @RequestMapping(value = "/api/delete", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult deleteActivity(String[] ids) {
        ResponseResult result = new ResponseResult();
        try {
            int rows = activityService.removeActivity(ids);
            if (rows > 0) {
                result.setCode(Constants.STATUS_OK);
                result.setMsg("删除成功");
            } else {
                result.setCode(Constants.STATUS_ERROR);
                result.setMsg("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Constants.STATUS_ERROR);
        }
        return result;
    }

    /*批量下载  兼容 选择下载  */
    @RequestMapping("/exportExcel")
    public void exportExcel(String[] ids, HttpServletResponse response) throws IOException {
        /*获取数据*/
        List<Activity> activities = new ArrayList<>();
        if (ids != null) {
            /*查ids*/
            activities = activityService.queryByIds(ids);
        } else {
            /*查所有*/
            activities = activityService.queryAll();
        }

        /*生产 POI的 DOM对象*/
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();

        /*样式*/
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);

        /*宽高*/
        sheet.setColumnWidth(0, 30 * 256);
        sheet.setColumnWidth(1, 30 * 256);
        sheet.setColumnWidth(2, 30 * 256);
        sheet.setColumnWidth(3, 30 * 256);
        sheet.setColumnWidth(4, 150 * 256);

        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cell = row0.createCell(0);
        cell.setCellValue("名称");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(1);
        cell.setCellValue("开始日期");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(2);
        cell.setCellValue("结束日期");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(3);
        cell.setCellValue("经费");
        cell.setCellStyle(cellStyle);
        cell = row0.createCell(4);
        cell.setCellValue("描述");
        cell.setCellStyle(cellStyle);

        /*遍历*/
        for (int i = 0; i < activities.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            cell = row.createCell(0);
            cell.setCellValue(activities.get(i).getName());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(1);
            cell.setCellValue(activities.get(i).getStartDate());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(2);
            cell.setCellValue(activities.get(i).getEndDate());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(3);
            cell.setCellValue(activities.get(i).getCost());
            cell.setCellStyle(cellStyle);
            cell = row.createCell(4);
            cell.setCellValue(activities.get(i).getDescription());
            cell.setCellStyle(cellStyle);
        }
        /*下载*/
        String finame = "市场活动" + DateUtils.formatDateTime(new Date()) + ".xls";
        /*设置响应头*/
        response.setHeader("content-type", "application/octet-stream");
        /*文件名与编码*/
        response.setHeader("content-disposition", "attachement;filename=" + URLEncoder.encode(finame, "UTF-8"));
        /*直接 通过 response的流 写入*/
        workbook.write(response.getOutputStream());
        /*刷新通道*/
        response.getOutputStream().flush();
    }

    /*导入*/
    @RequestMapping(value = "/api/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult importExcel(MultipartFile activityFile, HttpSession session) {
        ResponseResult result = new ResponseResult();
        try {
            /*使用 MultipartFile 中 的输入流 */
            HSSFWorkbook workbook = new HSSFWorkbook(activityFile.getInputStream());
            HSSFSheet sheet = workbook.getSheetAt(0);
            /*读取数据行*/
            List<Activity> activities = new ArrayList<>();
            /*获取当前用户信息*/
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                System.out.println(i);
                HSSFRow row = sheet.getRow(i);
                String name = row.getCell(0).getStringCellValue();
                String startDate = row.getCell(1).getStringCellValue();
                String endDate = row.getCell(2).getStringCellValue();
                String cost = row.getCell(3).getNumericCellValue() + "";
                String description = row.getCell(4).getStringCellValue();
                Activity activity = new Activity();
                activity.setName(name);
                activity.setStartDate(startDate);
                activity.setEndDate(endDate);
                activity.setCost(cost);
                activity.setDescription(description);

                activity.setId(UUIDUtils.getUUID());//主键
                activity.setOwner(user.getId());
                activity.setCreateBy(user.getId());
                activity.setCreateTime(DateUtils.formatDateTime(new Date()));
                activities.add(activity);
            }
            /*保存到数据库*/
            int rows = activityService.saveActivityList(activities);
            System.out.println(rows);
            result.setCode(Constants.STATUS_OK);
            result.setMsg("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("导入异常");
        }
        return result;
    }

    /*通过 activityid 获取  备注集合*/

    @RequestMapping("/api/remarkList")
    @ResponseBody
    public ResponseResult remarkList(String activityId) {
        ResponseResult result = new ResponseResult();

        List<ActivityRemark> remarkList = activityRemarkService.queryAllByActivityId(activityId);

        result.setCode(Constants.STATUS_OK);
        result.setData(remarkList);
        return result;
    }

    /*添加 备注*/
    @RequestMapping("/api/activityRemarkSave")
    @ResponseBody
    public ResponseResult activityRemarkSave(ActivityRemark activityRemark, HttpSession session) {
        ResponseResult result = new ResponseResult();
        activityRemark.setId(UUIDUtils.getUUID());
        activityRemark.setCreateTime(DateUtils.formatDateTime(new Date()));
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        activityRemark.setCreateBy(user.getId());
        activityRemark.setEditFlag("0");
        try {
            int rows = activityRemarkService.addActivityRemark(activityRemark);
            result.setCode(Constants.STATUS_OK);
        } catch (Exception e) {
            result.setCode(Constants.STATUS_OK);
            result.setMsg("保存备注失败");
        }
        return result;
    }


    /*删除备注*/
    @RequestMapping("/api/activityRemarkDelete")
    @ResponseBody
    public ResponseResult activityRemarkDelete(String remarkId) {
        ResponseResult result = new ResponseResult();
        try {
            int rows = activityRemarkService.removeRemark(remarkId);
            result.setCode(Constants.STATUS_OK);
        } catch (Exception e) {
            result.setCode(Constants.STATUS_ERROR);
            result.setMsg("备注删除失败");
        }

        return result;
    }

    @RequestMapping("/api/tranList")
    @ResponseBody
    public ResponseResult tranList(String owner,
                                   String activityName,
                                   String customerName,
                                   String stage,
                                   String type,
                                   String source,
                                   String contactsFullName,
                                   Integer pageNum,
                                   Integer pageSize) {
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 4 : pageSize;
        ResponseResult result = new ResponseResult();
        List<Tran> trans = tranService.queryPages(owner, activityName, customerName, stage, type, source, contactsFullName, pageNum, pageSize);
        Integer rows = tranService.queryCount(owner, activityName, customerName, stage, type, source, contactsFullName);
        int pages = (rows % pageSize == 0) ? rows % pageSize : (rows % pageSize + 1);
        Map<String, Object> data = new HashMap<>();
        data.put("trans", trans);
        data.put("rows", rows);
        data.put("pages", pages);
        data.put("pageNum", pageNum);
        data.put("pageSize", pageSize);
        result.setData(data);
        result.setCode(Constants.STATUS_OK);
        result.setMsg("成功");
        return result;
    }
}

